package com.isoft.illustrationsdraw.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.isoft.illustrationsdraw.Constants;
// import com.isoft.illustrationsdraw.dto.MessageDTO;
import com.isoft.illustrationsdraw.entity.Message;
import com.isoft.illustrationsdraw.service.ChatService;
import com.isoft.illustrationsdraw.service.FileService;
import com.isoft.illustrationsdraw.service.MessageService;

@Service
public class ChatServiceImpl implements ChatService {

    private final MessageService messageService;
    private final FileService fileService;
        
    public ChatServiceImpl(MessageService messageService, FileService fileService) {
        this.messageService = messageService;
        this.fileService = fileService;
    }

    @Override
    @Transactional
    public void saveMessage(Message message, MultipartFile file) throws IllegalArgumentException, IOException {
        try {
            boolean isSaved = messageService.save(message);
            if (!isSaved) {
                throw new IllegalArgumentException(Constants.Error.SAVE_MESSAGE_FAILED);
            }
            if (file == null) {
                return;
            }
            Long messageId = message.getId();

            var savedFiles = saveMedia(messageId, file);
            var path = savedFiles.get(0).getAbsolutePath();

            Message updateMedia = new Message();
            updateMedia.setId(messageId);

            updateMedia.setMediaUrl(path);
            messageService.updateById(updateMedia);

        } catch (Exception e) {
            throw e;
        }
    }

    private List<File> saveMedia(Long messageId, MultipartFile file) throws IllegalArgumentException, IOException {

        List<MultipartFile> files = new ArrayList<>();
        files.add(file);

        List<File> savedFiles = new ArrayList<>();
        try {
            var media = fileService.createDirectory(Constants.File.MESSAGE_MEDIA_DIR + messageId.toString());
            savedFiles = fileService.saveFiles(media, files);
            return savedFiles;
        } catch (Exception e) {
            for (File savedFile : savedFiles) {
                if (savedFile.exists()) {
                    savedFile.delete();
                }
            }
            throw e;
        }
    }

    // private void pushMessageToReceiver(MessageDTO message) {
    //     // Assuming the receiver's ID is stored in message.getReceiverId()
    //     String destination = "/queue/" + message.getReceiverId(); // WebSocket destination
    //     messagingTemplate.convertAndSend(destination, message); // Send the message to the receiver's WebSocket queue
    // }
}
